package com.ada.atomic;


import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

public class ApiCounter {
    private final Map<String, AtomicLong> counters = new ConcurrentHashMap<>();

    private Cache<String,AtomicLong> cache;

    public ApiCounter(){
        this.cache=  Caffeine.newBuilder()
                .expireAfterWrite(1, TimeUnit.SECONDS) // Cache data for 5 seconds
                .removalListener((key, value, cause) -> {
                    System.out.println(key);
                    // Write the count to the database when it's evicted from cache
                })
                .build();
    }


    public long increment(String apiName) {
        AtomicLong counter = counters.computeIfAbsent(apiName, k -> new AtomicLong(0));
        long updatedCount = counter.incrementAndGet();
        // Store the count in the in-memory cache (Caffeine) with eviction logic
        cache.put(apiName, counter);
        System.out.println(cache.estimatedSize());
        return updatedCount;
    }

    public static void main(String[] args) throws InterruptedException {
        ApiCounter counter=new ApiCounter();
        for (int i = 0; i < 100; i++) {
            counter.increment("ada"+i);
            Thread.sleep(100);
        }
        System.out.println(counter.getCount("ada"));



    }

    public long getCount(String apiName) {
        AtomicLong counter = counters.get(apiName);
        return (counter != null) ? counter.get() : 0;
    }

    // Write the count for a specific API to the database
    private void writeToDatabase(String apiName, long count) {
        String sql = "UPDATE api_counters SET count = ? WHERE api_name = ?";
    }
}
